package com.tyros.common.kit.string;

import java.util.HashMap;
import java.util.Map;

/**
 * @author zhangshuaiyin
 * @date 2022/3/21 15:30
 */
public class TemplateKit {

    /**
     * 模板字符串替换
     * <p>
     * 用法:
     * <pre>
     * String template = "短信验证码为 ${code}";
     * String placeholder = "${code}";
     * String value = "123456";
     * replace(template, placeholder, value); // 短信验证码为 123456
     * </pre>
     *
     * @param template    模板
     * @param placeholder 占位符
     * @param value       替换值
     */
    private static void replace(StringBuilder template, String placeholder, String value) {
        template.replace(template.indexOf(placeholder), template.indexOf(placeholder) + placeholder.length(), value);
    }

    /**
     * 模板字符串替换
     *
     * @param template          模板
     * @param placeholderValues 占位符对应值，key为占位符，value为要替换的值
     * @return 替换后的字符串
     */
    public static String replace(String template, Map<String, String> placeholderValues) {
        StringBuilder stringBuilder = new StringBuilder(template);
        placeholderValues.forEach((placeholder, value) -> replace(stringBuilder, placeholder, value));
        return stringBuilder.toString();
    }

    public static void main(String[] args) {
        String template = "用户 ${user} 你好，短信验证码为 ${code}";
        String placeholder1 = "${code}";
        String placeholder2 = "${user}";
        String value1 = "123456";
        String value2 = "zhang san";
        Map<String, String> map = new HashMap<>(4);
        map.put(placeholder1, value1);
        map.put(placeholder2, value2);
        System.out.println(TemplateKit.replace(template, map));
    }
}
